<template>
  <div style="height:6vh;padding:10px 20px;background-color:#fff;">
    <span style="line-height:60px;font-size:20px;">用户管理</span>
    <el-button
        type="primary"
        style="float:right;margin-top:10px;"
        @click="beforeAddUser">新建用户
    </el-button>
  </div>
  <!-- :before-close="handleClose"在弹窗关闭之前调用此自定义函数
   这样避免点击弹窗外部也能将弹窗关闭的问题 -->
  <el-dialog :title="dialogTitle"
             style="width: 1000px;padding:40px;"
             v-model="dialogVisible"
             :before-close="handleClose">
    <el-form label-position="top">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="用户名">
            <el-input
                placeholder="请输入用户名"
                v-model="saveUserForm.username"
                :disabled="saveUserForm.id!=null"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号">
            <el-input placeholder="请输入手机号" v-model="saveUserForm.phone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="邮箱">
            <el-input placeholder="请输入邮箱" v-model="saveUserForm.email"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄">
            <el-input placeholder="请输入年龄" v-model="saveUserForm.age"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="职级">
            <el-select
                placeholder="请选择"
                v-model="saveUserForm.level"
                @change="loadLeader">
              <el-option v-for="item in levelOptions" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="直属领导">
            <el-select placeholder="请选择" v-model="saveUserForm.parentId">
              <el-option v-for="item in leaderOptions"
                         :label="item.username" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="性别">
            <el-radio-group v-model="saveUserForm.gender">
              <el-radio border label="男" value="1" style="margin: 0"></el-radio>
              <el-radio border label="女" value="0"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="用户状态">
            <el-radio-group v-model="saveUserForm.status">
              <el-radio border label="启用" value="1" style="margin: 0;"></el-radio>
              <el-radio border label="禁用" value="0"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveUser">保存</el-button>
    </template>
  </el-dialog>
  <!-- 用户搜索卡片 -->
  <el-card style="margin: 20px; height: 70px">
    <el-form :inline="true">
      <el-form-item label="用户搜索" style="width: 220px;">
        <el-input
            placeholder="输入用户名"
            v-model="searchUserForm.username"
            @keydown.enter="loadUser"></el-input>
      </el-form-item>
      <el-form-item label="用户状态" style="width: 290px;">
        <el-select
            placeholder="请选择用户状态"
            v-model="searchUserForm.status"
            @change="loadUser">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadUser">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 用户数据表格卡片 -->
  <el-card style="margin: 20px;">
    <el-table :data="userArr">
      <el-table-column type="index" label="编号" width="80" align="center"></el-table-column>
      <el-table-column label="用户名" prop="username" align="center"></el-table-column>
      <el-table-column label="手机号" prop="phone" align="center"></el-table-column>
      <el-table-column label="加入时间" prop="createTime" align="center"></el-table-column>
      <el-table-column label="用户状态" prop="status" align="center">
        <template #default="scope">
          <el-switch
              active-value="1"
              inactive-value="0"
              v-model="scope.row.status"
              @change="changeStatus(scope.row.id,scope.row.status)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
              link type="primary"
              @click="resetPassword(scope.row.id)"
              :disabled="scope.row.level==40">密码重置
          </el-button>
          <el-button
              link type="primary"
              :disabled="scope.row.level==40"
              @click="editUser(scope.row.id)">编辑
          </el-button>
          <el-button
              link type="primary"
              :disabled="scope.row.level==40"
              @click="deleteUser(scope.row.id)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";

const dialogTitle = ref('新建用户');
const dialogVisible = ref(false);
const levelOptions = ref([
  {label: '员工', value: '10'},
  {label: '经理', value: '20'},
  {label: '总监', value: '30'},
  {label: '总裁', value: '40'}
]);
const leaderOptions = ref([
  // {username: 'AA', id: '101'},
  // {username: 'BB', id: '102'}
])

const saveUserForm = ref({
  username: '',
  phone: '',
  email: '',
  age: '',
  level: '',
  parentId: '',
  gender: '',
  status: ''
});

//每次点击"新建用户"按钮时调用:出弹窗+重置弹窗标题
const beforeAddUser = () => {
  dialogTitle.value = '新建用户';
  dialogVisible.value = true;
}

const saveUser = () => {
  let data = qs.stringify(saveUserForm.value);
  axios.post(BASE_URL + '/v1/user/save', data)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('保存成功!');
          //保存成功后,关闭弹窗
          dialogVisible.value = false;
          //清空已输入的表单数据
          saveUserForm.value = {};
          //保存成功后要重新加载用户数据,注意:新增与编辑后都需要重新加载!
          loadUser();
        } else {
          ElMessage.error(response.data.msg);
        }
      })
}

const handleClose = () => {
  if (confirm('确认要关闭本窗口吗?')) {
    //用户确认关闭后,关闭弹窗
    dialogVisible.value = false;
    //清空已输入的表单数据
    saveUserForm.value = {};
  }
}

const searchUserForm = ref({username: '', status: ''});
const userArr = ref([]);
const loadUser = () => {
  let data = qs.stringify(searchUserForm.value)
  axios.get(BASE_URL + '/v1/user/select?' + data)
      .then((response) => {
        if (response.data.code === 2000) {
          userArr.value = response.data.data;
          console.log(userArr.value)
        } else {
          ElMessage.error(response.data.msg);
        }
      })
}

//页面一加载完毕,立即执行
onMounted(() => {
  loadUser();
})

const resetSearch = () => {
  //清空之前的搜索内容
  searchUserForm.value = {};
  //重新加载数据
  loadUser();
}

//定义方法用来加载所选职级对应的可选直属领导数据
const loadLeader = () => {
  //问题:如果员工选择了直属领导,再切换职级,新加载出来的领导选项里没有之前的领导,无法显示出领导姓名
  //解决:每次新选择职级后,加载直属领导前,需要将之前选择的直属领导和可选领导数据清空,防止遗留数据
  saveUserForm.value.parentId = '';
  leaderOptions.value = [];
  //先拿到用户当前选择的职级,再+10才是上层可选领导的职级
  let level = parseInt(saveUserForm.value.level) + 10;
  //给后端发送查询请求,查出对应职级下的所有员工
  axios.get(BASE_URL + '/v1/user/select?level=' + level)
      .then((response) => {
        if (response.data.code == 2000) {
          //将请求回来的数据存入leaderOptions中
          leaderOptions.value = response.data.data;
        } else {
          ElMessage.error(response.data.msg);
        }
      })
}

//定义重置密码的方法 restful风格
const resetPassword = (userId) => {
  axios.post(BASE_URL + '/v1/user/update/password/' + userId)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('密码重置成功!');
        } else {
          ElMessage.error(response.data.msg);
        }
      })
}

const editUser = (id) => {
  dialogVisible.value = true;
  dialogTitle.value = '编辑用户';
  //先根据用户id查询出该用户的所有信息
  axios.get(BASE_URL + '/v1/user/select?id=' + id)
      .then((response) => {
        if (response.data.code == 2000) {
          //后端返回的是List<UserVO>,所以查一条数据的话拿的是集合的第一个元素data[0]
          saveUserForm.value = response.data.data[0];
          let level = parseInt(saveUserForm.value.level) + 10;
          //给后端发请求,获取直属领导有哪些人
          axios.get(BASE_URL + '/v1/user/select?level=' + level)
              .then((response) => {
                if (response.data.code == 2000) {
                  leaderOptions.value = response.data.data;
                } else {
                  ElMessage.error(response.data.msg);
                }
              })
        } else {
          ElMessage.error(response.data.msg);
        }
      })
}

const changeStatus = (userId, status) => {
  axios.post(BASE_URL + '/v1/user/update/status/' + userId + '/' + status)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('状态修改成功!');
        } else {
          ElMessage.error(response.data.msg);
        }
      })
}


const deleteUser = (userId) => {
  if (confirm('确认要删除该用户吗?')) {
    axios.post(BASE_URL + '/v1/user/delete/' + userId)
        .then((response) => {
          if (response.data.code == 2000) {
            ElMessage.success('删除成功!');
            //重新加载数据
            loadUser();
          } else {
            ElMessage.error(response.data.msg);
          }
        })
  }
}
</script>

<style scoped>

</style>